<template>
    <div>
        <NuxtLayout name="default">
            <template #panel>
                <!--                <TheSession />-->
            </template>

            <div class="flex h-full w-full">
                <div class="h-full flex-1 relative w-[75%]">
                    <div
                        class="online-chat-max-w h-full max-w-[1468px] flex-1 relative my-0 mx-auto"
                    >
                        <div
                            class="flex justify-between items-center px-[40px] absolute w-full h-[50px] online-chat-title"
                        >
                            <div class="flex items-center">
                                <div
                                    v-if="skillChat.name"
                                    @click="handeBackToAiChat"
                                    class="back-ai-chat-btn mr-2 text-sm"
                                >
                                    <i
                                        class="iconfont icon-tuichu mr-1"
                                        style="font-size: 12px"
                                    />
                                    <span>回到AI对话</span>
                                </div>
                                <div class="font-bold text-sm">
                                    <span>{{
                                        skillChat.name || '兴博士AI'
                                    }}</span>
                                </div>
                            </div>
                            <div>
                                <!--                            <div>相关专家</div>-->
                            </div>
                        </div>
                        <Chatting
                            ref="chattingRef"
                            :content-list="chatContentList"
                            :send-disabled="isReceiving"
                            :selectval="skillChat.selectval || sessionActive"
                            :avatar="
                                skillChat.currentIcon ||
                                appStore.config.chat.chat_logo
                            "
                            :isReceiving="isReceiving"
                            :chat-type="skillChat.chatType || 1"
                            :title="skillChat.chatTitle"
                            @close="chatClose"
                            @update="getChatList"
                            @content-post="contentPost"
                            @clean-chat-log="cleanChatLog"
                        >
                            <div
                                v-if="!chatContentList.length"
                                class="px-[50px]"
                            >
                                <div
                                    class="my-[20px] text-center text-[30px] font-medium"
                                >
                                    {{ appStore.getChatConfig.chat_title }}
                                </div>
                                <!--有对话记录或者是技能时候不显示-->
                                <div class="flex" v-if="!skillChat.selectval">
                                    <div
                                        v-for="item in exampleList.slice(0, 3)"
                                        :key="item.id"
                                        class="flex-1 mx-[10px]"
                                    >
                                        <div
                                            class="flex flex-col justify-center items-center mb-[20px]"
                                        >
                                            <img
                                                v-if="item.image"
                                                class="w-[58px] h-[58px]"
                                                :src="item.image"
                                                alt=""
                                            />
                                            <div
                                                class="text-[16px] font-medium mt-[16px]"
                                            >
                                                {{ item.name }}
                                            </div>
                                        </div>
                                        <div>
                                            <div
                                                v-for="sample in item.sample"
                                                :key="sample.id"
                                                class="sample-item mb-[20px] p-[10px] flex justify-center cursor-pointer line-clamp-1"
                                                @click="
                                                    contentPost(sample.content)
                                                "
                                            >
                                                {{ sample.content }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </Chatting>
                    </div>
                </div>
                <ChatSkills ref="chatSkillsRef" @selected="handleSelectSkill" />
            </div>

            <TheGuidedPopup ref="guidedPopupRef" />
        </NuxtLayout>
    </div>
</template>
<script setup lang="ts">
import { getchatLog, samplesLists, cleanChat, chatSendText } from '@/api/chat'
import { useUserStore } from '~~/stores/user'
import feedback from '~~/utils/feedback'
import { useAppStore } from '~/stores/app'
import useRouteQuery from '~/composables/useRouteQuery'
import TheSession from '@/components/the-session'

// const { key } = useRouteQuery()
//
// if (key) {
//     localStorage.setItem('MOUSE_KEY', key)
// }
// 初始化条件往上提一下
const fromSkillPageStorage = JSON.parse(sessionStorage.getItem('skill') || '{}')
const skillChat = ref({
    selectval: null,
    chatTitle: null,
    currentIcon: null,
    chatType: null,
    ...fromSkillPageStorage
})
sessionStorage.removeItem('skill')
const chatSkillsRef = ref()
const userStore = useUserStore()
const appStore = useAppStore()
const router = useRouter()
const route = useRoute()

//对话记录列表

//对话框ref
const chattingRef = ref(null)
const guidedPopupRef = shallowRef()
const {
    sessionActive,
    sessionAdd,
    currentSession,
    sessionEdit,
    getSessionLists,
    initSessionActive
} = await useSessionList()

await useAsyncData(() => getSessionLists(), {
    default() {
        return []
    },
    immediate: true
})
//问题示例列表
const { data: exampleList } = await useAsyncData(() => {
    return []
    // samplesLists({ type: 1 })
})

const handleSelectSkill = ({ id, title, image, name }: any) => {
    chatContentList.value = []
    skillChat.value = {
        selectval: id,
        chatTitle: title,
        name,
        currentIcon: image,
        chatType: 3
    }
    nextTick(async () => {
        await getChatList()
        chattingRef.value.scrollToBottom()
    })
}

// 回到ai对话
const handeBackToAiChat = async () => {
    chatContentList.value = []
    // 重置技能的选择
    skillChat.value = {
        selectval: null,
        chatTitle: null,
        name: '',
        currentIcon: null,
        chatType: null
    }
    // inactive 右边技能的高亮
    chatSkillsRef.value.setActiveSkill('')
    // 选择无skill的chat
    await initSessionActive()
    await nextTick(async () => {
        await getChatList()
        chattingRef.value.scrollToBottom()
    })
}
//获取聊天记录
const { data: chatContentList, refresh: getChatList } = await useAsyncData(
    () =>
        getchatLog(
            skillChat.value.selectval
                ? {
                      type: 3,
                      other_id: skillChat.value.selectval,
                      page_type: 0
                  }
                : {
                      type: 1,
                      category_id: sessionActive.value,
                      page_type: 0
                  }
        ),
    {
        transform(data) {
            return data.lists.map((item: any) => {
                if (item.type == 1) {
                    return { ...item, from_avatar: userStore.userInfo.avatar }
                } else {
                    return {
                        ...item,
                        from_avatar: appStore.config.chat.chat_logo
                        // from_avatar:
                        //     skillChat.value.currentIcon ||
                        //     appStore.config.chat.chat_logo
                    }
                }
            })
        },
        default() {
            return []
        }
    }
)

const isReceiving = ref(false)
//发送问题
const contentPost = async (userInput: any, model?: string, deep = false) => {
    if (!userStore.isLogin) return userStore.toggleShowLogin(true)
    if (isReceiving.value) return
    if (sessionActive.value === 0) {
        await sessionAdd()
    }
    if (currentSession.value === '新的会话') {
        await sessionEdit(sessionActive.value, userInput)
    }
    chatContentList.value.push(
        skillChat.value.selectval
            ? {
                  type: 3,
                  content: userInput,
                  other_id: skillChat.value.selectval,
                  from_avatar: userStore.userInfo.avatar
              }
            : {
                  type: 1,
                  content: userInput,
                  from_avatar: userStore.userInfo.avatar
              }
    )
    chatContentList.value.push({
        type: 2,
        loading: true,
        content: [],
        from_avatar: appStore.config.chat.chat_logo,
        id: ''
    })
    isReceiving.value = true
    try {
        await chatSendText(
            skillChat.value.selectval
                ? {
                      model: model || '',
                      question: userInput,
                      type: 3,
                      deep,
                      other_id: skillChat.value.selectval
                  }
                : {
                      model: model || '',
                      question: userInput,
                      type: 1,
                      deep,
                      other_id: sessionActive.value
                  },
            {
                onstart(reader) {
                    streamReader = reader
                },
                onmessage(value) {
                    value
                        .trim()
                        .split('data:')
                        .forEach(async (text) => {
                            if (text !== '') {
                                try {
                                    const dataJson = JSON.parse(text)
                                    const {
                                        id: chatId,
                                        code,
                                        event,
                                        data,
                                        index,
                                        incremental
                                    } = dataJson
                                    console.log(data)
                                    if (event == 'error' && code === 101) {
                                        guidedPopupRef.value?.open()
                                    } else if (event == 'error') {
                                        feedback.msgError(data)
                                    }

                                    let chatIndex =
                                        chatContentList.value.findIndex(
                                            (item) => item.id === chatId
                                        )
                                    if (chatIndex === -1) {
                                        chatIndex =
                                            chatContentList.value.length - 1

                                        chatContentList.value[chatIndex].id =
                                            chatId
                                    }

                                    if (data) {
                                        if (
                                            !chatContentList.value[chatIndex]
                                                .content[index]
                                        ) {
                                            chatContentList.value[
                                                chatIndex
                                            ].content[index] = ''
                                        }
                                        chatContentList.value[
                                            chatIndex
                                        ].content[index] = incremental
                                            ? chatContentList.value[chatIndex]
                                                  .content[index] + data
                                            : data
                                    }

                                    if (event === 'finish') {
                                        chatContentList.value[
                                            chatIndex
                                        ].loading = false
                                        return
                                    }
                                } catch (error) {}
                            }
                        })
                },
                onclose() {
                    isReceiving.value = false
                    setTimeout(getChatList, 400)
                }
            }
        )
        chattingRef.value.cleanInput()
    } catch (error) {
        isReceiving.value = false
        chatContentList.value.splice(chatContentList.value.length - 2, 2)
    }

    nextTick(() => {
        chattingRef.value.scrollToBottom()
    })
}

let streamReader: ReadableStreamDefaultReader<Uint8Array> | null = null
const chatClose = (index?: number) => {
    streamReader?.cancel()
    if (index) {
        chatContentList.value[index].loading = false
    }
    isReceiving.value = false
}

//清空会话
const cleanChatLog = async () => {
    await feedback.confirm('确定清空对话？')
    // 如果有选择某个技能
    if (skillChat.value.selectval) {
        await cleanChat({ type: 3, other_id: skillChat.value.selectval })
    } else {
        await cleanChat({ type: 1, category_id: sessionActive.value })
    }
    chatContentList.value = []
}

watch(sessionActive, async () => {
    chatClose()
    await getChatList()
    await nextTick()
    chattingRef.value.scrollToBottom()
})

onMounted(async () => {
    if (route.query.cid || route.query.user_sn) {
        const cid: any = useCookie('cid')
        const user_sn: any = useCookie('user_sn')
        cid.value = route.query.cid
        user_sn.value = route.query.user_sn
        await nextTick()
        userStore.checkShare()
    }
    await nextTick()
    chattingRef.value.scrollToBottom()

    const autoSendMsg = sessionStorage.getItem('autoSendMsg')
    if (autoSendMsg) {
        chattingRef.value.setInput(autoSendMsg)
        sessionStorage.removeItem('autoSendMsg')
    }

    if (skillChat.value.selectval) {
        chatSkillsRef.value.setActiveSkill(skillChat.value.selectval)
    }
})

definePageMeta({
    layout: false
})
</script>
<style lang="scss" scoped>
@import 'assets/styles/fix_online_css.scss';

.container-tip {
    border: 1px solid #fb9a3b;
}
.item {
    :hover {
        color: #fb9a3b;
    }
}
.sample-item {
    border-radius: 12px;
    background: #fff;
    border: 1px solid #eef2f2;
    box-shadow: 0 2px 8px #f5f6f8;
}
.back-ai-chat-btn {
    background: white;
    cursor: pointer;
    border: 1px solid #e1e1e3;
    padding: 3px 10px;
    border-radius: 5px;
    color: #828a95;
    &:hover {
        color: black;
    }
}
</style>
